package com.plian.system.service.cqzc.existapproval;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.*;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.fr.bonds.ExistApprovalDTO;
import com.plian.system.entity.fr.bonds.BondsApply;
import com.plian.system.entity.fr.bonds.BondsPlan;
import com.plian.system.entity.fr.bonds.ExistApproval;
import com.plian.system.mapper.fr.bonds.BondsApplyMapper;
import com.plian.system.mapper.fr.bonds.BondsPlanMapper;
import com.plian.system.mapper.fr.bonds.ExistApprovalMapper;
import com.plian.system.service.sys.code.IFormCodeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 说明：发债申请
 */
@Slf4j
@Service
@AllArgsConstructor
public class ExistApprovalService extends ServiceImpl<ExistApprovalMapper, ExistApproval> {

    private ExistApprovalMapper existApprovalMapper;
    private BondsApplyMapper bondsApplyMapper;
    private BondsPlanMapper bondsPlanMapper;
    private IFormCodeService formCodeService;

    /**
     * 保存
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ExistApproval saveExistApproval(ExistApprovalDTO dto) throws Exception{
        // 先保存主体
        ExistApproval entity = new ExistApproval();
        BeanUtils.copyProperties(dto,entity);
        entity.setCode(formCodeService.getCode(FormTypeConstant.CQZC_EXIST_APPROVAL));
        entity.setCreateCompanyId(TokenUtil.getTokenOrgId());
        entity.setCreateUser(TokenUtil.getTokenUserId());
        DateTime now = DateUtil.date();
        entity.setCreateTime(now);
        entity.setUpdateUser(TokenUtil.getTokenUserId());
        entity.setUpdateTime(now);
        this.save(entity);
        // 再查询发债申请、发债计划并update
        if(StringUtils.isNotBlank(dto.getBondsApplyId())){
            BondsApply bondsApply = bondsApplyMapper.selectById(dto.getBondsApplyId());
            if(null == bondsApply) throw new Exception("该发债申请不存在");
            if(null == bondsApply.getExistApprovalId()){
                bondsApply.setExistApprovalId(entity.getId());
                bondsApplyMapper.updateById(bondsApply);
            }
        }

        if(StringUtils.isNotBlank(dto.getBondsPlanId())){
            BondsPlan bondsPlan = bondsPlanMapper.selectById(dto.getBondsPlanId());
            if(null == bondsPlan) throw new Exception("该发债计划不存在");
            if(null == bondsPlan.getExistApprovalId()){
                bondsPlan.setExistApprovalId(entity.getId());
                bondsPlanMapper.updateById(bondsPlan);
            }
        }
        return entity;

    }

    /**
     * 修改
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ExistApproval editExistApproval(ExistApprovalDTO dto) throws Exception{
        // 先查发债申请id和发债计划id有没有更换
        if(StringUtils.isNotBlank(dto.getBondsApplyId())){
            BondsApply bondsApply = bondsApplyMapper.selectById(dto.getBondsApplyId());
            if(null == bondsApply) throw new Exception("该发债申请不存在");
            if(!dto.getId().equals(bondsApply.getExistApprovalId())){
                bondsApply.setExistApprovalId(dto.getId());
                bondsApplyMapper.updateById(bondsApply);
            }
        }
        if(StringUtils.isNotBlank(dto.getBondsPlanId())){
            BondsPlan bondsPlan = bondsPlanMapper.selectById(dto.getBondsPlanId());
            if(null == bondsPlan) throw new Exception("该发债计划不存在");
            if(!dto.getId().equals(bondsPlan.getExistApprovalId())){
                bondsPlan.setExistApprovalId(dto.getId());
                bondsPlanMapper.updateById(bondsPlan);
            }
        }
        ExistApproval entity = new ExistApproval();
        BeanUtils.copyProperties(dto,entity);
        entity.setUpdateUser(TokenUtil.getTokenUserId());
        entity.setUpdateTime(DateUtil.date());
        this.updateById(entity);

        return entity;
    }



    @Transactional(rollbackFor = Exception.class)
    public void delByIds(List<String> ids) throws Exception {
        for (String id : ids) {
            // 查询发债申请与发债计划是否使用该批文
            Integer count = bondsApplyMapper.selectCount(new LambdaQueryWrapper<BondsApply>().eq(BondsApply::getExistApprovalId, id));
            if(count > 0) throw new Exception("存在使用该批文的发债申请，无法删除");
            Integer count1 = bondsPlanMapper.selectCount(new LambdaQueryWrapper<BondsPlan>().eq(BondsPlan::getExistApprovalId, id));
            if(count1 > 0) throw new Exception("存在使用该批文的发债计划，无法删除");
            existApprovalMapper.deleteById(id);
        }
    }



}